package com.tater.zkwatcher;

import com.tater.config.NettyConfig;
import com.tater.pojo.ResponseTime;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Component
public class ZKWatcher implements IZkChildListener,Runnable {
    ZkClient zkClient ;

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    private boolean startTask=false;

    @Override
    public void run() {
        serviceList = zkClient.getChildren(NettyConfig.SERVER_NODE);
        for (String s : serviceList) {
            String path=NettyConfig.SERVER_NODE+"/"+s;
          ResponseTime time= zkClient.readData(path);
          if (time.getCallTime().plusSeconds(5L).isBefore(LocalDateTime.now())){
              time.setCallTime(LocalDateTime.now());
              time.setDoneTime(0L);
                zkClient.writeData(path,time);
//              System.out.println("更新服务时间为0："+path);
          }
        }
    }

    private List<String> serviceList=new ArrayList<>();
    @PostConstruct
    private void connect(){
        zkClient = new ZkClient(NettyConfig.ZK_ADDRESS);
        System.out.println("消费者连接到ZK服务器");
        zkClient.subscribeChildChanges(NettyConfig.SERVER_NODE,this);
        System.out.println("消费者拉取服务列表");
        serviceList = zkClient.getChildren(NettyConfig.SERVER_NODE);
        for (String s : serviceList) {
            System.out.println("服务列表："+s);
        }

        executorService.scheduleAtFixedRate(this,5,5, TimeUnit.SECONDS);

    }

    public ZkClient getZkClient() {
        return zkClient;
    }


    public void setData(String path,Object data){

        boolean exists = zkClient.exists(path);
        if (exists){
            zkClient.writeData(path,data);
        }
    }

    @Override
    public void handleChildChange(String s, List<String> list) throws Exception {
        System.out.println("node:"+s);
        for (String s1 : list) {
            System.out.println("---:"+s1);
        }
        this.serviceList=list;
    }

    public List<String> getServiceList() {
        return serviceList;
    }
}
